<?php

namespace App\Http\Controllers;

use App\Http\Resources\PermissionResource;
use App\Http\Traits\CheckPermission as CheckPermissionTrait;
use App\Models\Permission;
use App\Models\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PermissionController extends Controller
{
    use CheckPermissionTrait;

    protected $resource = 'permissions';

    public function __construct()
    {
        $this->middleware('auth.api');
    }

    /**
     * 获取权限列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $query = Permission::with('menu');

        if ($request->has('name')) {
            $query->where('name', 'like', '%' . $request->name . '%');
        }

        if ($request->has('code')) {
            $query->where('code', 'like', '%' . $request->code . '%');
        }

        if ($request->has('type')) {
            $query->where('type', $request->type);
        }

        if ($request->has('resource')) {
            $query->where('resource', 'like', '%' . $request->resource . '%');
        }

        if ($request->has('action')) {
            $query->where('action', $request->action);
        }

        if ($request->has('menu_id')) {
            $query->where('menu_id', $request->menu_id);
        }

        $permissions = $query->orderBy('id', 'desc')
            ->paginate($this->getPageSize($request));

        // 使用Resource格式化分页数据，包括时间字段
        $permissions->setCollection(
            $permissions->getCollection()->map(function ($permission) {
                return (new PermissionResource($permission))->resolve(request());
            })
        );

        return $this->success($permissions, '获取成功');
    }

    /**
     * 创建权限
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        // 检查新增权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_CREATE);

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|unique:permissions',
            'type' => 'required|string|in:' . implode(',', [
                Permission::TYPE_MENU,
                Permission::TYPE_BUTTON,
                Permission::TYPE_DATA,
            ]),
            'action' => 'nullable|string',
            'resource' => 'nullable|string',
            'menu_id' => 'nullable|exists:menus,id',
            'remark' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        $data = $request->all();
        
        // 如果没有提供code，根据resource和action自动生成
        if (empty($data['code']) && !empty($data['resource']) && !empty($data['action'])) {
            $data['code'] = Permission::generatePermissionCode($data['resource'], $data['action']);
        }

        $permission = Permission::create($data);

        // 清除权限缓存
        $permissionService = app(\App\Services\PermissionService::class);
        $permissionService->clearAllPermissionCache();

        return $this->success(new PermissionResource($permission->load('menu')), '创建成功');
    }

    /**
     * 获取权限详情
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $permission = Permission::with('menu')->findOrFail($id);
        return $this->success(new PermissionResource($permission), '获取成功');
    }

    /**
     * 更新权限
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $permission = Permission::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|unique:permissions,code,' . $id,
            'type' => 'required|string|in:' . implode(',', [
                Permission::TYPE_MENU,
                Permission::TYPE_BUTTON,
                Permission::TYPE_DATA,
            ]),
            'action' => 'nullable|string',
            'resource' => 'nullable|string',
            'menu_id' => 'nullable|exists:menus,id',
            'remark' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        $data = $request->all();
        
        // 如果没有提供code，根据resource和action自动生成
        if (empty($data['code']) && !empty($data['resource']) && !empty($data['action'])) {
            $data['code'] = Permission::generatePermissionCode($data['resource'], $data['action']);
        }

        $permission->update($data);

        // 清除权限缓存
        $permissionService = app(\App\Services\PermissionService::class);
        $permissionService->clearAllPermissionCache();

        return $this->success(new PermissionResource($permission->load('menu')), '更新成功');
    }

    /**
     * 删除权限
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $permission = Permission::findOrFail($id);
        
        // 检查是否被角色使用
        if ($permission->roles()->exists()) {
            return $this->error('权限已被角色使用，无法删除', 400);
        }

        $permission->delete();

        // 清除权限缓存
        $permissionService = app(\App\Services\PermissionService::class);
        $permissionService->clearAllPermissionCache();

        return $this->success(null, '删除成功');
    }

    /**
     * 获取所有权限（用于下拉选择）
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function all()
    {
        $permissions = Permission::with('menu')
            ->orderBy('id', 'desc')
            ->get();

        return $this->success(PermissionResource::collection($permissions), '获取成功');
    }
}

